package cn.huhst.cas.weisiqian.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import cn.huhst.cas.weisiqian.service.UserService;
import cn.huhst.cas.weisiqian.util.JSON;

@WebServlet("/DeleteUser.do")
public class DeleteUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Logger logger = Logger.getLogger(DeleteUser.class);
	private UserService userservice = null;

	public DeleteUser() {
		super();
		userservice = new UserService();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String username = request.getParameter("username");
		JSON json = new JSON();
		if (username == null || "".equals(username)) {
			json.put("status", "error");
			json.put("msg", "用户信息不合法");
			logger.error("请求删除的用户姓名不合法，用户姓名为空");
		} else {
			logger.info("请求删除用户：" + username);
			HttpSession session = request.getSession();
			if (username.equals(session.getAttribute("username"))) {
				logger.error("不能删除本人账号");
				json.put("status", "error");
				json.put("msg", "不能删除本人账号");
			} else {
				boolean result = userservice.deleteUser(username);
				if (result) {
					logger.info("删除用户" + username + "成功");
					json.put("status", "ok");
					json.put("msg", "删除用户" + username + "成功");
				} else {
					logger.info("删除用户" + username + "失败");
					json.put("status", "error");
					json.put("msg", "删除用户" + username + "失败");
				}
			}
		}
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(json);
	}

}
